

import axios from "axios";
import { Loading,Message  } from 'element-ui';
import router from "@/router"
let token = "";   // 用户有效的登录的身份信息 
const baseURL = "http://localhost:3000";
// axios.defaults.baseURL = baseURL ;   // 基路径  反向代理不能使用基路径 
axios.defaults.headers.common['Authorization'] = token ;    // Authorization auth 身份验证 
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';  // POST  文档数据格式 

let  loading = null;
function showLoading(){
    loading = Loading.service({
        lock: true,
        text: '请求中...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)',
        fullscreen:true,
    });    
}

function showSuccess(msg){
    loading.close();
    Message({
        message: msg || '请求成功',
        center: true,
        type: 'success',
        // showClose: true,
        duration:800
    })
}
function showError(msg){
    loading.close();
    Message({
        message: msg || '请求失败',
        center: true,
        type: 'error',
        duration:800
        // showClose: true,
    })
}
// Interceptors  拦截器 

// Add a request interceptor  请求之前拦截  
axios.interceptors.request.use(function (config) {

    
    config.headers.token = sessionStorage.token?sessionStorage.token:'';   // 把后端给你的token 带到 后端 
    showLoading();
    return config;
    
    // 请求发送之前 调 loading
  }, function (error) {
    // 请求 失败   关闭loading 
    showError("请求失败")
    return Promise.reject(error);
});

// Add a response interceptor  响应之后的拦截 
axios.interceptors.response.use(function (response) {
    
    // 弹框 msg
    console.log(response)
    if(response.data.type==1){
        showSuccess(response.data.msg);
    }else{
        if(response.data.type==0){
            showError(response.data.msg)
        }else{
            showSuccess(response.data.msg);
        }
    }

    if(response.data.code=="3000"){
        // 重定向到登录 
        router.push({name:"login"})
        location.reload(); 
    }
    
    
    return response;
  }, function (error) {
    // 提示失败 
    showError("响应失败-服务器异常")
    return Promise.reject(error);
});
 

export   { axios  };